package com.example.newsapp.adapter;

import static com.example.newsapp.constant.NetConstant.BASE_URL;

import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.newsapp.activity.NewsDetailActivity;
import com.example.newsapp.model.NewsItem;
import com.example.newsapp.R;

import java.util.List;

public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.NewsViewHolder> {
    private List<? extends NewsItem> newsList;

    public NewsAdapter(List<? extends NewsItem> newsList) {
        this.newsList = newsList;
    }

    @NonNull
    @Override
    public NewsViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_news, parent, false);
        return new NewsViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull NewsViewHolder holder, int position) {
        NewsItem newsItem = newsList.get(position);
        holder.titleTextView.setText(newsItem.getTitle());
        holder.timeTextView.setText(newsItem.getTime());
        holder.authorTextView.setText(newsItem.getAuthor());
        String imageUrl = BASE_URL + newsItem.getImageUrl();
        Glide.with(holder.itemView.getContext())
                .load(imageUrl)
                .error(R.drawable.error) // 加载失败显示的图片
                .into(holder.newsImageView);

        // 设置点击事件
        holder.itemView.setOnClickListener(v -> {
            Intent intent = new Intent(v.getContext(), NewsDetailActivity.class);
            // TODO string
            intent.putExtra("news_id", newsItem.getId());
            intent.putExtra("news_title", newsItem.getTitle());
            intent.putExtra("news_time", newsItem.getTime());
            intent.putExtra("news_image", newsItem.getImageUrl());
            intent.putExtra("news_author", newsItem.getAuthor());
            v.getContext().startActivity(intent);
        });
    }

    @Override
    public int getItemCount() {
        return newsList.size();
    }

    static class NewsViewHolder extends RecyclerView.ViewHolder {
        TextView titleTextView;
        TextView timeTextView;
        ImageView newsImageView;
        TextView authorTextView;

        public NewsViewHolder(@NonNull View itemView) {
            super(itemView);
            titleTextView = itemView.findViewById(R.id.titleTextView);
            timeTextView = itemView.findViewById(R.id.timeTextView);
            newsImageView = itemView.findViewById(R.id.newsImageView);
            authorTextView = itemView.findViewById(R.id.authorTextView);
        }
    }
}